<?php

/**
 * 影院周简报
 */
class Action
{
    private $per_page = 100;

    /**
     * 显示列表
     */
    public function index() {
        $page_no = $order_type = $search_filter = $include_zzb_code = $is_excel = $province_ids= null;

        //给变量初始化一个值,如果获取到了其get值则重新赋值
        extract(URLTracker::init(array(
            'page_no' => 1,
            'search_filter' => array(),
            'order_type' => -1,
            'include_zzb_code' => -1,
            'is_excel' => 0
        )));

        // 拼装搜索条件
        $filter['type'] = '100';
        $filter['is_delete'] = 1;

        if($include_zzb_code > -1){
            if($include_zzb_code == 0){
                $filter['zzb_id'] = 0;
            }else{
                $filter['zzb_id >'] = 0;
            }
        }

        if (isset($search_filter['title']) && $search_filter['title']) {
            $filter['`title` LIKE '] = '%' . $search_filter['title'] . '%';
        }

        if (isset($search_filter['province_id']) && $search_filter['province_id']) {
            $filter['province_id'] = $search_filter['province_id'];
            $province_ids = join(',', $search_filter['province_id']);
        }

        //筛选商店数据
        $store_list = _model('store')->getFields('id', $filter);
        if(!$store_list){
            $store_list = array(-1);
        }

        //获取省市
        $area = _model('region')->getList(array('status' => 1));
        $areaList = array();
        $provinceList = array();
        foreach($area as $k => $v){
            if($v['depth'] == 1){
                $provinceList[$v['area_code']] = $v['area'];
            }
            $areaList[$v['area_code']] = $v['area'];
        }

        //排序
        $order_string = ' ORDER BY `zzb_id` DESC ';
        if($order_type == 1){
            $order_string = ' ORDER BY `box_office` DESC ';
        }
        if($order_type == 2){
            $order_string = ' ORDER BY `viewers` DESC ';
        }
        if($order_type == 3){
            $order_string = ' ORDER BY `order_money` DESC ';
        }
        if($order_type == 4){
            $order_string = ' ORDER BY `spp` DESC ';
        }

        $wlist = $this->get_weeks_by_start_end_date('2016-10-1', date('Y-m-d'));
        //获取相关周的起始结束日期
        if (!isset($search_filter['week'])) {
            $week_key = array_keys($wlist);
            $search_filter['week'] = end($week_key);
        }
        $sectionDate = $wlist[$search_filter['week']];

        $count_sql = 'select count(*) as num from (select c.store_id FROM `cinema_daily_report` c left join `store` s on c.store_id = s.id  left join cinema_zzb cz on s.zzb_id= cz.zzb_code where c.date >= "' . $sectionDate['start'] . '" and date <= "' . $sectionDate['end'] . '" and c.store_id in (' . implode(',', $store_list) . ') group by c.store_id) as cdr';
        $count = _model('cinema_daily_report')->getAll($count_sql)[0]['num'];

        if($is_excel){
            $this->per_page = 3000;
        }
        //分页配置
        $pager = new Pager($this->per_page);
        if ($pager->generate($count)) {
            Response::assign('pager', $pager);
        }

        $sql = 'select store_id, s.zzb_id, s.title, s.title_branch, cz.cinema_name, cz.circuit, cz.investment_company, s.add_time, s.province_id, s.city_id, s.district_id, sum(box_office) as box_office, sum(viewers) as viewers, sum(order_money) as order_money FROM `cinema_daily_report` c left join `store` s on c.store_id = s.id  left join cinema_zzb cz on s.zzb_id= cz.zzb_code where c.date >= "' . $sectionDate['start'] . '" and date <= "' . $sectionDate['end'] . '" and c.store_id in (' . implode(',', $store_list) . ') group by c.store_id ' . $order_string . ' ' . $pager->getLimit($page_no);
        $cinema_week_report = _model('cinema_daily_report')->getAll($sql);

        if ($cinema_week_report) {
            foreach ($cinema_week_report as $k => $v) {
                $cinema_week_report[$k]['province'] = $areaList[$v['province_id']];
                $cinema_week_report[$k]['city'] = $areaList[$v['city_id']];
                $cinema_week_report[$k]['county'] = $areaList[$v['district_id']];
                if ($cinema_week_report[$k]['viewers'] > 0 && $cinema_week_report[$k]['order_money'] > 0) {
                    $cinema_week_report[$k]['spp'] = (float)$cinema_week_report[$k]['order_money'] / ((float)$cinema_week_report[$k]['viewers']);
                } else {
                    $cinema_week_report[$k]['spp'] = null;
                }
            }
        }

        if($is_excel){
            $this->export_csv($cinema_week_report);
            return;
        }

        Response::assign('store_list', $cinema_week_report);
        Response::assign('search_filter', $search_filter);
        Response::assign('weekList', $wlist);
        Response::assign('order_type', $order_type);
        Response::assign('provinceList', $provinceList);
        Response::assign('include_zzb_code', $include_zzb_code);
        Response::assign('province_ids', $province_ids);
        Response::display('admin/cinema_daily_brief.html');
    }

    public function chart() {
        $province_ids = an_request('province_ids');
        $province_query = array();
        if($province_ids){
            $province_query = explode(',', $province_ids);
        }

        //获取近6周的起始日期和结束日期
        $numweek = 6;
        $numweekdata = $this->get_weeks_by_before_numweek($numweek);
        krsort($numweekdata);
        $six_weeks = array();
        foreach ($numweekdata as $k => $v) {
            $six_weeks[] = substr($v['start'], -5) . ' - ' . substr($v['end'], -5);
        }

        //获取所有省
        $area = _model('region')->getList(array('status' => 1, 'depth' => 1, 'area_code' => $province_query));
        $province_code_list = array();
        $province_name_list = array();
        foreach($area as $k => $v) {
            $province_code_list[] = $v['area_code'];
            $province_name_list[] = $v['area'];
        }

        //获取各省近6周的下单总金额
        $money_list = array();
        foreach ($province_code_list as $k => $v) {
            $amount_arr = array();
            foreach ($numweekdata as $nk => $nv) {
                $filter['province'] = $v;
                $filter['date >= '] = $nv['start'];
                $filter['date <= '] = $nv['end'];
                $amount = _model('cinema_daily_report')->getFields('order_money', $filter);
                $amount = $amount ? format_money(array_sum($amount)) : 0.00;
                $amount_arr[] = $amount;
            }
            $money_list[] = $amount_arr;
        }

        $returnArray = array(
            'six_weeks' => $six_weeks,
            'line_name' => $province_name_list,
            'money_list' => $money_list
        );
        return_data(1, $returnArray);
    }

    /**
     * 获取指定日期之间的各个周
     */
    public function get_weeks_by_start_end_date($sdate, $edate) {
        $oldsdate = $sdate;
        $range_arr = array();
        do {
            $weekinfo = $this->get_weekinfo_by_date($sdate);
            $start = $weekinfo['week_start_day'];
            $end = $weekinfo['week_end_day'];
            if (date('Y-m-d', strtotime($start)) >= date('Y-m-d', strtotime($oldsdate))) {
                $range_arr[] = array('start' => $start, 'end' => $end);
            }
            $sdate = date('Y-m-d', strtotime($sdate) + 7 * 86400);
        } while (date('Y-m-d', strtotime($end) + 7 * 86400) <= $edate);
        //} while ($end <= $edate);
        return $range_arr;
    }

    /**
     * 获取前几周的开始日期和结束日期
     */
    public function get_weeks_by_before_numweek($num) {
        $sdate = date('Y-m-d');
        $range_arr = array();
        $i = 0;
        do {
            $weekinfo = $this->get_weekinfo_by_date($sdate);
            $start = $weekinfo['week_start_day'];
            $end = $weekinfo['week_end_day'];
            if (date('Y-m-d') >= date('Y-m-d', strtotime($end))) {
                $range_arr[] = array('start' => $start, 'end' => $end);
                $i++;
            }
            $sdate = date('Y-m-d', strtotime($sdate) - 7 * 86400);
        } while ($i < $num);
        return $range_arr;
    }

    /**
     * 根据指定日期获取所在周的起始时间和结束时间
     */
    public function get_weekinfo_by_date($date) {
        $idx = strftime('%u', strtotime($date));
        $mon_idx = $idx - 1;
        $sun_idx = $idx - 7;
        return array(
            'week_start_day' => strftime('%Y-%m-%d', strtotime($date) - $mon_idx * 86400),
            'week_end_day' => strftime('%Y-%m-%d', strtotime($date) - $sun_idx * 86400),
        );
    }

    private function export_csv($data){
        if(!$data){
            return;
        }

        $li[] = explode(',', 'APP ID,专资办编码,影院名称(APP),影院别名(APP),专资办名称,签约时间,省,市,区,院线,影投公司,票房/元,观影人次,进货金额,SPP');

        foreach($data as $k=>$v){
            $li[] = array($v['store_id'],$v['zzb_id'],$v['title'],$v['title_branch'],$v['cinema_name'],$v['add_time'],$v['province'],$v['city'],$v['county'],$v['circuit'],$v['investment_company'],$v['box_office'],$v['viewers'],$v['order_money'],$v['spp']);
        }

        _widget('tools.excel')->export('影院周数据_'.time(), array(
            array(
                'name' => '影院周报表',
                'data' => array(
                    'data' => $li,
                ),
            )
        ));
    }
}
